
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies!=null){
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals("uname")){
                pageContext.setAttribute("uname",cookie.getValue() );
            }
            if (name.equals("pwd")){
                pageContext.setAttribute("pwd",cookie.getValue() );
            }

        }
    }


%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单验证</title>
    <style>
        span{
            color: red;
            font-size: 12px;
        }
    </style>
</head>
<body>
<form id="login" action="login" method="POST" onsubmit="return checkForm()">
    <table border="1px" cellpadding="10px" cellspacing="0" align="center" width="500px">
        <caption><h2>用户登录</h2></caption>
        <tr>
            <td>账号</td>
            <td>
                <input type="text" name="uname" id="username" value="${uname}"  onblur="checkName(this,'username_msg','账号不能为空')">
                <span id="username_msg"></span>
            </td>
        </tr>
        <tr>
            <td>密码</td>
            <td>
                <input type="password" name="pwd" id="pwd" value="${pwd}" onblur="checkPwd(this,'pwd_msg','密码不能为空')">
                <span id="pwd_msg"></span>
            </td>
        </tr>
        <tr align="center">
            <td colspan="2">
                <input type="submit" id="sub" value="登录">
                <input type="reset" id="ret" value="取消">
            </td>
        </tr>
    </table>
</form>
<script>
    /*
     非空验证
     el:表示验证的文本框元素
     spanId：表示错误消息显示的span标签的id号
     msg:表示错误消息内容
    */
    function validate(el,spanId,msg){
        //获取显示错误消息的span标签
        var span = document.getElementById(spanId);
        //清空
        span.innerText = "";
        //获取文本框中数据
        var val = el.value;
        //判断
        if(val==null||val==""){
            span.innerText = msg;
            return false;
        }
        return true;
    }

    var user_flag = false;//标识用户名是否验证通过
    var pwd_flag = false;//标识密码是否验证通过
    //验证用户名
    function checkName(el,spanId,msg){
        user_flag = validate(el,spanId,msg);
    }
    //验证密码
    function checkPwd(el,spanId,msg){
        pwd_flag = validate(el,spanId,msg);
    }

    //提交表单
    function checkForm(){
        if(user_flag&&pwd_flag){
            return true;
        }
        return false;
    }
</script>
</body>
</html>
